<template>
	<view class="container-wrapper">
		<u-navbar title=" " :autoBack="true" bgColor="#3B67A5" :fixed="true" :placeholder="true">
			<view class="u-nav-slot flex-row y-center" slot="left">
				<u-icon name="arrow-left" size="19" color="#fff"></u-icon>
				<text class="label">车牌号</text>
				<text class="value">{{tblViolationRecord.plate||'未知'}}</text>
			</view>
		</u-navbar>
		<view class="card-section">
			<view class="flex-row y-center title-wrapper">
				<u--image src="/static/waiting.png" width="44rpx" height="44rpx"></u--image>
				<text class="title">违停信息</text>
			</view>
			<view class="from-wrapper">
				<u--form labelPosition="left" labelWidth="150rpx" :model="tblViolationRecord" ref="uForm">
					<u-form-item label="车主姓名" prop="name">
						<u--input readonly v-model="cVehicle.name||'未知'" placeholder="" border="none"></u--input>
					</u-form-item>
					<u-form-item label="联系电话" prop="moble">
						<u--input readonly :value="$commonUtil.truncateStrReplaceStar(cVehicle.moble)||'未知'"
							placeholder="" border="none"></u--input>
					</u-form-item>
					<u-form-item label="车辆类型" prop="registrationType">
						<u--input v-model="cVehicle.registrationType||'未知'" placeholder="" border="none"></u--input>
					</u-form-item>
					<u-form-item label="所在校区" prop="campusCode">
						<u--input readonly
							:value="tblViolationRecord.campusCode==1?'华西':tblViolationRecord.campusCode==2?'望江':'江安'"
							placeholder="" border="none"></u--input>
					</u-form-item>
					<u-form-item label="违停地点" prop="location">
						<u--input readonly v-model="tblViolationRecord.location" placeholder=""
							border="none"></u--input>
					</u-form-item>
					<u-form-item label="上报人员" prop="recorderName">
						<u--input readonly v-model="tblViolationRecord.recorderName" placeholder=""
							border="none"></u--input>
					</u-form-item>
					<u-form-item label="登记时间" prop="violationTime">
						<u--input readonly v-model="tblViolationRecord.violationTime" placeholder=""
							border="none"></u--input>
					</u-form-item>
					<u-form-item label="违停描述" prop="description">
						<u--input readonly v-model="tblViolationRecord.description" placeholder=""
							border="none"></u--input>
					</u-form-item>

					<u-form-item label=" " labelPosition="top" prop="password">
						<view @click="previewImageFn(tblViolationRecord.violationPhotos)" class="img-wrapper"
							v-if="tblViolationRecord.violationPhotos"
							v-for="(item,index) in tblViolationRecord.violationPhotos">
							<u--image :showLoading="true" :src="item" width="80px" height="80px"></u--image>
						</view>

					</u-form-item>
				</u--form>
			</view>
		</view>
		<view class="card-section">
			<view class="flex-row y-center title-wrapper">
				<u--image src="/static/note.png" width="44rpx" height="46rpx"></u--image>
				<text class="title">处置信息登记</text>
			</view>
			<view class="from-wrapper">
				<u--form errorType="toast" labelPosition="left" labelWidth="150rpx" :model="tblViolationHandling"
					:rules="rules" ref="uForm">
					<u-form-item label="处置人" borderBottom required v-if="tblViolationHandling.handlerName">
						<u--input readonly v-if="tblViolationRecord.status == 0" v-model="userInfo.nickName"
							placeholder="" border="none"></u--input>
						<u--input readonly v-else v-model="tblViolationHandling.handlerName" placeholder=""
							border="none"></u--input>
					</u-form-item>
					<u-form-item label="处置时间" v-if="tblViolationHandling.handleTime" prop="handleTime" borderBottom>
						<u--input readonly v-model="tblViolationHandling.handleTime" placeholder=""
							border="none"></u--input>
					</u-form-item>
					<!-- <u-form-item label="处置时间" prop="handleTime" borderBottom>
						<u--input v-if="tblViolationRecord.status == 0" readonly  v-model="currentTime"
							placeholder="" border="none"></u--input>
						<u--input v-else  readonly v-model="tblViolationHandling.handleTime" placeholder=""
							border="none"></u--input>
					</u-form-item> -->

					<u-form-item label="违停描述" labelPosition="top" prop="description" borderBottom>
						<view style="position: relative;width: 100%;" v-if="tblViolationRecord.status == 0">
							<u-textarea style="padding-right: 30rpx;" autoHeight
								v-model="tblViolationHandling.resultDescription" :maxlength="500" placeholder="请输入违停描述"
								border="none"></u-textarea>
							<view style="position: absolute;right: 0;top: 16rpx;">
								<picker mode="selector" :range="descriptionList" v-model="descriptionIndex"
									range-key="dictValue" @change="onPickerChange($event,'description')">
									<u-icon name="arrow-down-fill" color="#666" size="14"></u-icon>
								</picker>
							</view>
						</view>
						<u-textarea style="background-color: transparent;" v-else autoHeight
							v-model="tblViolationHandling.resultDescription" :maxlength="500" placeholder="请输入违停描述"
							border="none" disabled></u-textarea>
					</u-form-item>
					<u-form-item label=" " labelPosition="top" prop="violationPhotos">
						<view class="mt16" v-if="tblViolationRecord.status == 0">
							<u-upload :compressed="true" :fileList="tblViolationHandling.violationPhotos"
								@afterRead="afterRead" @delete="deletePic" name="1" multiple :maxCount="10">
								<image src="/static/upload.png" mode="aspectFill" style="width: 200rpx;height: 152rpx;">
								</image>
							</u-upload>
						</view>
						<view v-else class="flex-row y-center wrap">
							<view class="img-wrapper" @click="previewImageFn(tblViolationHandling.violationPhotos)"
								v-if="tblViolationHandling.violationPhotos"
								v-for="(item,index) in tblViolationHandling.violationPhotos">
								<u--image :showLoading="true" :src="item" width="80px" height="80px"></u--image>
							</view>
						</view>
					</u-form-item>
				</u--form>
			</view>
		</view>
		<u-button class="custom-style" v-if="tblViolationRecord.status == 0" text="提交" @click="onSubmit"></u-button>
		<uniLoading v-if="loadingCover" bgColor="#fff"></uniLoading>
	</view>
</template>

<script>
	import {
		getViolationDetailsApi,
		registerDisposalInfoApi,
		disposalDescriptionApi
	} from '@/apis/disposal.js';
	import {
		getInfoApi
	} from '@/apis/common.js';
	export default {
		data() {
			return {
				userInfo: {},
				isSubmit: true,
				loadingCover: false,
				tblViolationHandling: {
					violationPhotos: [],
					resultDescription: ''
				},
				tblViolationRecord: {

				},
				descriptionList: [],
				descriptionIndex: 0,
				cVehicle: {},
				id: '',
				// currentTime: this.getCurrentFormattedTime(),
				rules: {
					'violationPhotos': {
						type: 'array',
						min: 1,
						required: true,
						message: '请上传图片',
						trigger: ['change', 'blur']
					},
					'resultDescription': {
						type: 'string',
						required: true,
						message: '请填写描述',
						trigger: ['blur', 'change']
					},
				},

			}
		},
		onLoad(options) {
			this.id = options.id || '';
			this.getInfo();
			this.getData();
			this.disposalDescription();
		},

		methods: {
			async getInfo() {
				try {
					let resp = await getInfoApi();
					this.userInfo = resp.user;
				} catch (e) {
					console.log(`获取用户信息${e.message}`, 'background:orange')
				}
			},
			// 预览图片
			previewImageFn(list) {
				if (list.length) {
					// 预览图片
					uni.previewImage({
						urls: list,
						longPressActions: {
							itemList: ["发送给朋友", "保存图片", "收藏"],
							success: function(data) {},
							fail: function(err) {
								console.log(err.errMsg);
							},
						},
					});
				}
			},
			getCurrentFormattedTime() {
				// 创建一个新的 Date 对象（代表当前日期和时间）
				var now = new Date();
				// 获取各个部分
				var year = now.getFullYear();
				var month = now.getMonth() + 1; // JavaScript的月份从0开始，所以我们需要将结果加1
				var day = now.getDate();
				var hours = now.getHours();
				var minutes = now.getMinutes();
				var seconds = now.getSeconds();

				// 将月份、日期、小时、分钟和秒数格式化为两位数
				month = month < 10 ? '0' + month : month;
				day = day < 10 ? '0' + day : day;
				hours = hours < 10 ? '0' + hours : hours;
				minutes = minutes < 10 ? '0' + minutes : minutes;
				seconds = seconds < 10 ? '0' + seconds : seconds;
				// 拼接出一个格式为 "YYYY-MM-DD HH:MM:SS" 的字符串
				var formattedTime = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
				return formattedTime;
			},
			async getData() {

				try {
					let resp = await getViolationDetailsApi({
						id: this.id
					})
					let tblViolationHandling = resp.tblViolationHandling || {};
					let tblViolationRecord = resp.tblViolationRecord || {};
					if (tblViolationHandling.violationPhotos) {
						let violationPhotosArr = tblViolationHandling.violationPhotos.split(',');
						tblViolationHandling.violationPhotos = violationPhotosArr
					} else {
						tblViolationHandling.violationPhotos = []
					}
					if (tblViolationRecord.violationPhotos) {
						let violationPhotosArr = tblViolationRecord.violationPhotos.split(',');
						tblViolationRecord.violationPhotos = violationPhotosArr
					}
					this.tblViolationHandling = tblViolationHandling;
					this.tblViolationRecord = tblViolationRecord;

					this.cVehicle = resp.cVehicle || {}
					this.tblViolationHandling.resultDescription = this.tblViolationHandling.resultDescription || this
						.descriptionList[0].dictValue;

					console.log(this.tblViolationHandling, 'this.tblViolationHandling')
				} catch (e) {
					console.log(`%获取详情，${e.message},'background:orange'`)
				} finally {
					this.loadingCover = false;
				}
			},
			//数据字典
			async disposalDescription() {
				try {
					let resp = await disposalDescriptionApi();
					this.descriptionList = resp.data;
					this.tblViolationHandling.resultDescription = this.descriptionList[0].dictValue;
				} catch (e) {
					console.log(`%c数据字典${e.message}`, 'background:orange')
				} finally {

				}
			},
			onPickerChange(e, source) {
				this.descriptionIndex = e.detail.value;
				this.tblViolationHandling.resultDescription = this.descriptionList[this.descriptionIndex].dictValue;
			},
			// 删除图片
			deletePic(event) {
				this.tblViolationHandling.violationPhotos.splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let len = 0;
				let fileListLen = this.tblViolationHandling.violationPhotos.length
				this.isSubmit = false;
				lists.map((item) => {
					this.tblViolationHandling.violationPhotos.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					console.log(result, 'result')
					let item = this.tblViolationHandling.violationPhotos[fileListLen]
					this.tblViolationHandling.violationPhotos.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++;
					len++;
					if (len == lists.length) {
						this.isSubmit = true;
					}
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: `${this.$config.baseUrl}/common/upload`, // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						header: {
							Authorization: uni.getStorageSync('token')
						},
						formData: {},
						success: (res) => {
							let resp = JSON.parse(res.data)
							console.log(resp, 'res---')
							setTimeout(() => {
								resolve(resp.url)
							}, 1000)
						}
					});
				})
			},
			//提交
			onSubmit() {
				this.$refs.uForm.validate().then((res) => {
					this.confirmSave();
				}).catch(errors => {
					console.log(errors, 'errors')
				})

			},

			async confirmSave() {
				if (!this.isSubmit) {
					uni.showToast({
						title: '图片还在上传中，请稍后提交',
						mask: true,
						icon: 'none'
					})
					return;
				}
				uni.showLoading({
					title: '提交中',
					mask: true
				})
				try {
					let params = JSON.parse(JSON.stringify(this.tblViolationHandling));
					params.violationRecordId = this.id;
					if (params.violationPhotos?.length) {
						let violationPhotos = params.violationPhotos;
						let img = []
						violationPhotos.map((val) => {
							img.push(val.url)
						})
						params.violationPhotos = img.join(',')
					}
					// params.handleTime = this.getCurrentFormattedTime()
					let resp = await registerDisposalInfoApi(params);
					uni.showToast({
						title: '处置成功',
						icon: 'none'
					})
					uni.navigateBack()
				} catch (e) {
					console.log(`%提交违停记录,${e.message},'background:orange'`)
				} finally {
					uni.hideLoading()
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	.container-wrapper {
		width: 100%;
		min-height: 100%;
		background: #FAFAFA;
		padding: 0 30rpx;

		.img-wrapper {
			margin-right: 20rpx;
			border-radius: 10rpx;
			overflow: hidden;
		}

		.u-nav-slot {
			color: #FFFFFF;

			.label {
				font-size: 28rpx;
				color: #FFFFFF;
			}

			.value {
				font-weight: bold;
				font-size: 34rpx;
				color: #FFFFFF;
				margin-left: 20rpx;
			}
		}

		/deep/.u-textarea {
			padding: 0;
			padding-top: 10rpx;
		}

		.card-section {
			.title-wrapper {
				height: 78rpx;

				.title {
					font-size: 28rpx;
					color: #141414;
					margin-left: 12rpx;
				}
			}
		}

		.from-wrapper {
			padding: 0 30rpx;
			background-color: #fff;
			border-radius: 15rpx;



			/deep/.u-input__content__field-wrapper__field {
				text-align: right !important;
			}

			.address-btn {
				font-size: 26rpx;
				color: #3B67A5;
				margin-right: 10rpx;
			}
		}

		.custom-style {
			background-color: #3B67A5;
			font-weight: 400;
			font-size: 28rpx;
			color: #FFFFFF;
			border-radius: 15rpx;
			margin-top: 40rpx;
		}
	}
</style>